package com.zzc.controller;

import com.zzc.domain.Staff;
import com.zzc.service.impl.StaffServiceImpl;
import com.zzc.util.UpLoad;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


@Controller
public class StaffController {

    @Autowired
    StaffServiceImpl staffService;

    @Autowired
    UpLoad upLoad;

    @GetMapping("/getstaff")
    public String getAllStaff(Model model) {
        model.addAttribute("staffs", staffService.getAllStaff());
        return "staff/allStaff";
    }

    @GetMapping("/addstaff")
    public String addStaff(Model model) {
        model.addAttribute("staffid",staffService.getStaffCount()+202100);
        return "staff/addStaff";
    }

    @PostMapping("/uploadstaff")
    public String upLoadStaff(String name, String birth,
                              int staffId, String address,
                              int gender, String phoneNum,
                              String weChat, String partment,
                              MultipartFile file) throws IOException {
        String uploadPath = upLoad.upload(file);

        Staff staff = new Staff(staffId, name, phoneNum, weChat, address, partment, gender, birth, uploadPath);
        staffService.addStaff(staff);

        return "staff/addStaff";
    }

    @GetMapping("/editstaff/{staffid}")
    public String getEditStaff(@PathVariable("staffid") int staffId, Model model){

        model.addAttribute("staff",staffService.findOneById(staffId));
        return "staff/editStaff";
    }

    @PostMapping("/updatestaff")
    @ResponseBody
    public String upDateStaff(String name, String birth,
                              int staffId, String address,
                              int gender, String phoneNum,
                              String weChat, String partment,
                              MultipartFile file) throws IOException {
        if (file.isEmpty()){
            Staff staff = staffService.findOneById(staffId);
            String uploadPath = staff.getStaffPicture();
            Staff staff1 = new Staff(staffId,name,phoneNum,weChat,address,partment,gender,birth,uploadPath);
            staffService.editStaff(staff1);
        }else {
            String uploadPath = upLoad.upload(file);

            Staff staff = new Staff(staffId,name,phoneNum,weChat,address,partment,gender,birth,uploadPath);

            staffService.editStaff(staff);
        }
        return null;
    }
}
